
const router = require('koa-router')()
const jwt = require('jsonwebtoken')
var svgCaptcha = require('svg-captcha');
const formidable = require('formidable')
const fs = require('fs');
const path = require('path')
const mime = require('mime-types');
const secret = '&*^R*G&(FRDwp4eg3'   //secret 加密
const timeout = 1000*60 //时效 1分钟

//格式化文件大小
function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
//检验token是否过期
function checkToken(token){
  if(token){
    let payload =jwt.verify(token,secret)
    let {time,timeout} = payload
    let date = new Date().getTime()
    if(date-time<=timeout){
      return true
    }else{
      return false
    }
  }
}

router.post('/token',async(ctx,next)=>{
  let token =ctx.request.headers["authorization"]
  
  if(!checkToken(token)){
    ctx.body ={code:401,msg:"token过期,请重新登录"}
  }else{
    ctx.body={code:200}
  }
})

router.get('/', async (ctx, next) => {
  let sql = 'select * from user where name=? and age=?'
  let name = 'zhangsan'
  let age = 15
  let result = await ctx.db.query(sql,[name,age])
  console.log(result);

  ctx.body = result
})

//图片列表数据
router.get('/getlist',async(ctx,next)=>{
  const filePath = path.join(__dirname,'../public/images')
  let sql = 'select * from images'
  let res = await ctx.db.query(sql)
  // console.log(res);
  // let filesList = fs.readdirSync(filePath)
  // console.log(filesList);
  let files=[]

  if(res){
    res.map((item)=>{
      console.log(item.img_name);
      let size = formatBytes(fs.statSync(filePath+'/'+item.img_name).size)  //转换文件大小格式
      let type = mime.lookup(filePath+'/'+item.img_name)                    //获取文件类型
      let file = fs.readFileSync(filePath+'/'+item.img_name,'base64')       //获取图片
      files.push({id:item.img_id,imgUrl:file,name:item.img_name,type:type,size:size})     
      
    })
    ctx.body = {'files':files,'code':200}

  }

})

//删除图片
router.post('/deletefile',async(ctx,next)=>{
  let id = ctx.request.body.id
  let fileName = ctx.request.body.filename
  if(id){
    let sql = 'delete from images where img_id=?'
    await ctx.db.query(sql,[id])
    const filePath = path.join(__dirname,'../public/images')
    let file = filePath+'/'+fileName
    fs.unlinkSync(file)
  
  return ctx.body = {'code':200,'msg':'删除成功'}
  }else{
    return ctx.body={'code':404,'msg':'无此条数据'}
  }
})



//上传图片 
router.post('/upload',async(ctx,next)=>{
  const form = new formidable.IncomingForm()
  form.keepExtensions = true
  form.multiples=true
  let token =  ctx.request.headers["authorization"]


    if(checkToken(token)){ 
      if(
        form.parse(ctx.req,(err,fields,files)=>{  //另存上传的文件
          for(key in files){
            let file = files[key]
            const filePath = file.filepath;
            const fileName = Date.now()+'-' + file.originalFilename;
            let sql = 'insert into images(img_name,img_date) values(?,?)'
            ctx.db.query(sql,[fileName,new Date().toLocaleDateString()])
            const reader = fs.createReadStream(filePath)
            const write= fs.createWriteStream(`./public/images/${fileName}`)
            reader.pipe(write)
          }
          return result = true
        })
      )ctx.body = {'code':200,'msg':'上传成功'}
    }else{
      ctx.body ={'code':401,'msg':'token过期'}
    }
  
})


//验证码
router.get('/captcha',async(ctx,next)=>{
  var captcha = svgCaptcha.create()
  ctx.session.captcha = captcha.text
  ctx.body = captcha.data
  console.log(captcha.text)
})

//用户管理列表
router.get('/getusers',async(ctx,next)=>{
  let sql = 'select * from adminusers'
  let res = await ctx.db.query(sql)
  // let filename = path.join(__dirname,"../public/users.json")
  // let data = fs.readFileSync(filename)
  // let res = JSON.parse(data)

  ctx.body = {'code':200,'msg':res}

})

//更新数据
router.post('/updata',async(ctx,next)=>{
  let row = ctx.request.body
  row.edit = false
  console.log(row)
  let sql = 'update adminusers set user=?,phone=?,mail=?,address=? where id=?'
  await ctx.db.query(sql,[row.user,row.phone,row.mail,row.address,row.id])
  // let filename = path.join(__dirname,"../public/users.json")
  // let data =  fs.readFileSync(filename)
  // let res = JSON.parse(data)
  // //根据id找到索引
  // let index = res.findIndex(item=>item.id==row.id)
  // //从索引开始删除一条数据，并把row加入进去，即替换
  // res.splice(index,1,row)
  // fs.writeFileSync(filename,JSON.stringify(res))
  ctx.body={'code':200,"msg":"编辑成功"}

})

//添加用户数据
router.post('/addusers', async(ctx,next)=>{
  let row = ctx.request.body
  console.log(row);
  let sql = 'insert into adminusers(user,phone,mail,address) values(?,?,?,?)'
  await ctx.db.query(sql,[row.user,row.phone,row.mail,row.address])
  // let filename = path.join(__dirname,"../public/users.json")
  // let data = fs.readFileSync(filename)
  // let res = JSON.parse(data)
  // //把新数据放进去 
  // if(res.length!==0){
  //   var id = res[res.length-1].id +1 //id为数组中最后一个数据的id+1
  // }else{
  //   id = 0
  // }
  // row.id = id
  // row.edit = false
  // res.push(row)
  // fs.writeFileSync(filename, JSON.stringify(res))
  ctx.body={'code':200,'msg':"添加成功"}

})


//删除某个用户数据
router.post('/deleteuser',async(ctx,next)=>{
  let id = ctx.request.body.id
  let sql='delete from adminusers where id=?'
  await ctx.db.query(sql,[id])
  // let filename = path.join(__dirname,"../public/users.json")
  // let data = fs.readFileSync(filename)
  // let res = JSON.parse(data)
  // //根据条件删除一项
  // let result = res.filter(item=>{
  //   return item.id!==id
  // })
  // //把剩余的数据存储
  // fs.writeFileSync(filename,JSON.stringify(result))
  ctx.body={"code":200,"msg":'删除成功'}
})


//登录
router.post('/login', async (ctx, next) => {
  let sql = 'select * from loginusers where user=? and password=?'
  let userName= ctx.request.body.userName
  let pwd= ctx.request.body.pwd
  let res = await ctx.db.query(sql,[userName,pwd])
  let code = ctx.request.body.code
  if(res){
    var result = res.some(item=>{
      if(item.user == userName && item.password == pwd){
        return true
      }
    })
  }

  if(result){
    if(code == ctx.session.captcha){
      // 创建token 一小时后过期
      let payload = {user:userName,time:new Date().getTime(),timeout}
      let token = jwt.sign(payload,secret)
      return ctx.body = {'code':200,'msg':'登录成功','token':token}
    }else{
      return ctx.body = {'code':301,'msg':'验证码错误','token':'error'}
    }
  }else{
    return ctx.body = {'code':302,'msg':'用户名或密码错误','token':'error'}
  }


})
router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})
module.exports = router
